<template>
	<view class="login-view">
		<!-- wd-form不支持label-width属性，wot UI V1.10.0 -->
		<wd-form ref="formRef" :model="form" :rules="rules">
			<wd-cell-group border>
				<wd-input label="用户名" prefix-icon="user" label-width="100px" prop="login" v-model="form.login"
					placeholder="请输入用户名" />
				<wd-input label="密码" prefix-icon="lock-on" label-width="100px" prop="password" show-password
					v-model="form.password" placeholder="请输入密码" />
			</wd-cell-group>
			<view class="footer">
				<wd-button type="primary" size="large" @click="onSubmit" block>提交</wd-button>
			</view>
		</wd-form>
	</view>

</template>

<script lang="ts" setup>
	import { ref } from 'vue'
	import { Login } from '@/types/user'
	import { FormRules } from '@/uni_modules/wot-design-uni/components/wd-form/types'
	import { postLogin } from '@/common/api/api'
	import { useUserStore } from '@/stores/user';

	//表单相关
	const formRef = ref()
	const form = ref<Login>({
		login: '',
		password: ''
	})
	const rules = ref<FormRules>({
		login: [{ required: true, message: '请填写用户名' }],
		password: [{ required: true, message: '请填写密码' }],
	})
	
	
	const user = useUserStore()//缓存

	async function onSubmit() {
		try {
			const { valid, errors } = await formRef.value.validate();
			console.log(valid, errors);
			if (valid) {
				const res = await postLogin(form.value);
				if(res.success){
					user.setUser(res.data)
					if(user.backUrl){
						uni.reLaunch({ url: user.backUrl })
					}
					else{
						uni.navigateBack()
					}
				}
			}
		} catch (error) {
			console.error(error);//大概率是请求异常抛出
		}
	}
</script>

<style lang="scss">
	.login-view {
		.footer {
			padding: 20rpx;
		}
	}
</style>